package com.tanhua.server.service;

import com.aliyun.oss.OSSClient;
import com.tanhua.common.config.AliyunConfig;
import com.tanhua.server.vo.AudioUploadResult;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;

//语音文件上传到oss服务器的处理类
@Service
public class AudioUploadService {
    // 允许上传的格式
    private static final String[] VOICE_TYPE = new String[]{".m4a", ".mp3",
            ".avi"};

    @Autowired
    private OSSClient ossClient;
//导入阿里云配置文件
    @Autowired
    private AliyunConfig aliyunConfig;
    //上传语音到oss,大小100kb
    public AudioUploadResult upload(MultipartFile uploadFile) {
//语音文件上传类对象
        AudioUploadResult fileUploadResult = new AudioUploadResult();

        //语音文件做校验，对后缀名
        boolean isLegal = false;
//判断是否为语音文件
        for (String type : VOICE_TYPE) {
            if (StringUtils.endsWithIgnoreCase(uploadFile.getOriginalFilename(),
                    type)) {
                isLegal = true;
                //结束
                break;
            }
        }
//不是语音文件则不传
        if (!isLegal) {
            fileUploadResult.setStatus("error");
            return fileUploadResult;
        }

        // 文件新路径
        String fileName = uploadFile.getOriginalFilename();
        String filePath = getFilePath(fileName);

        // 上传到阿里云
        try {
            // 目录结构：images/2018/12/29/xxxx.jpg
            ossClient.putObject(aliyunConfig.getBucketName(), filePath, new ByteArrayInputStream(uploadFile.getBytes()));
        } catch (Exception e) {
            e.printStackTrace();
            //上传失败
            fileUploadResult.setStatus("error");
            return fileUploadResult;
        }

        // 上传成功
        fileUploadResult.setStatus("done");
        fileUploadResult.setName(this.aliyunConfig.getUrlPrefix() + filePath);
        fileUploadResult.setSid(String.valueOf(System.currentTimeMillis()));

        return fileUploadResult;
    }
    //从oss库中获取语音请求地址
    private String getFilePath(String sourceFileName){
        //创建当前时间对象
        DateTime dateTime = new DateTime();
        return "voice/" + dateTime.toString("yyyy")
                + "/" + dateTime.toString("MM") + "/"
                + dateTime.toString("dd") + "/" + System.currentTimeMillis() +
                RandomUtils.nextInt(100, 9999) + "." +
                //根据当前时间生成路径
                StringUtils.substringAfterLast(sourceFileName, ".");
    }

}
